//
//  URL.swift
//  CooperSwift
//
//  Created by 计海峰 on 2021/4/26.
//

import Foundation
import AVKit

public extension URL {
    
    /// 获取query参数（扩展属性）
    var queryParameters: [String: String]? {
        guard let components = URLComponents(url: self,     resolvingAgainstBaseURL: false), let queryItems =   components.queryItems else { return nil }
    
        var items: [String: String] = [:]
    
        for queryItem in queryItems {
            items[queryItem.name] = queryItem.value
        }
    
        return items
    }
    
    /// 添加query参数
    func appendingQueryParameters(_ parameters: [String: String]) -> URL {
        var urlComponents = URLComponents(url: self,    resolvingAgainstBaseURL: true)!
        var items = urlComponents.queryItems ?? []
        items += parameters.map({ URLQueryItem(name: $0,    value: $1) })
        urlComponents.queryItems = items
        return urlComponents.url!
    }
    
    /// 添加query参数
    mutating func appendQueryParameters(_ parameters: [String: String]) {
        self = appendingQueryParameters(parameters)
    }
    
    /// 通过key获取query参数的值
    func queryValue(for key: String) -> String? {
        let stringURL = self.absoluteString
        guard let items = URLComponents(string: stringURL)?.queryItems else { return nil }
        for item in items where item.name == key {
            return item.value
        }
        return nil
    }
    
    /// 删除所有的path components返回新的URL
    func deletingAllPathComponents() -> URL {
        var url: URL = self
        for _ in 0..<pathComponents.count - 1 {
            url.deleteLastPathComponent()
        }
        return url
    }
    
    /// 删除所有的path components
    mutating func deleteAllPathComponents() {
        for _ in 0..<pathComponents.count - 1 {
           deleteLastPathComponent()
          }
    }
    
    /// 获取视频某一刻的缩略图
    func thumbnail(fromTime time: Float64 = 0) -> UIImage? {
        let imageGenerator = AVAssetImageGenerator(asset: AVAsset(url: self))
        let time = CMTimeMakeWithSeconds(time, preferredTimescale: 1)
        var actualTime = CMTimeMake(value: 0, timescale: 0)

        guard let cgImage = try? imageGenerator.copyCGImage(at: time, actualTime: &actualTime) else {
            return nil
        }
        return UIImage(cgImage: cgImage)
    }

}
